package com.qiniuyun.threedgenerator.util;

import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Component
public class ModelCacheUtils {

    // 生成文本输入的缓存键
    public static String generateTextCacheKey(String text, String format) {
        String content = text + "|" + format;
        return DigestUtils.md5DigestAsHex(content.getBytes());
    }

    // 生成图片输入的缓存键
    public static String generateImageCacheKey(MultipartFile imageFile, String parameters) {
        try {
            String content = imageFile.getOriginalFilename() + "|" +
                    imageFile.getSize() + "|" +
                    (parameters != null ? parameters : "");
            return DigestUtils.md5DigestAsHex(content.getBytes());
        } catch (Exception e) {
            throw new RuntimeException("生成图片缓存键失败", e);
        }
    }

    // 计算文本相似度（用于相似缓存查找）
    public static double calculateTextSimilarity(String text1, String text2) {
        // 使用Jaccard相似度或余弦相似度
        Set<String> words1 = new HashSet<>(Arrays.asList(text1.toLowerCase().split("\\s+")));
        Set<String> words2 = new HashSet<>(Arrays.asList(text2.toLowerCase().split("\\s+")));

        Set<String> intersection = new HashSet<>(words1);
        intersection.retainAll(words2);

        Set<String> union = new HashSet<>(words1);
        union.addAll(words2);

        return union.isEmpty() ? 0.0 : (double) intersection.size() / union.size();
    }
}